package cn.nexd.app.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;

import cn.nexd.app.NexdApplication;
import cn.nexd.app.activity.inter.IMainActivityView;
import cn.nexd.app.arsenal.R;
import cn.nexd.app.arsenal.fragment.SettingFragment;
import cn.nexd.app.model.ExpandableModel;
import cn.nexd.app.model.MallModel;
import cn.nexd.app.perimission.CheckPermission;
import cn.nexd.app.presenter.ICollectionPresenterImpl;
import cn.nexd.app.presenter.IMallPresenterImpl;
import cn.nexd.app.presenter.inter.ICollectionPresenter;
import cn.nexd.app.presenter.inter.IMallPresenter;
import cn.nexd.app.util.DateUtil;
import cn.nexd.app.widget.circularprogressbutton.CircularProgress;
import cn.nexd.app.widget.circularprogressbutton.CircularProgressButton;
import de.hdodenhof.circleimageview.CircleImageView;


public class MainActivity extends BaseActivity implements View.OnClickListener, View.OnLongClickListener, NavigationView.OnNavigationItemSelectedListener, IMainActivityView {

    private ICollectionPresenter iCollectionPresenter;
    private EditText etInputFloorName;
    private TextView tvEnvironmentWifi;
    private TextView tvEnvironmentBeacon;
    private CircularProgressButton btnStartEnd;
    private CircularProgress drawable;
    private AnimatorSet currentAnimation;
    private TextView selectedMallName;
    private View viewSelectBuildingLayout;
    private TextView tvSelectBuilding;
    private TextView tvDevInfo;

    private ActionBarDrawerToggle drawerToggle;
    private boolean isRunning = false;
    private boolean animatorRunning = false;

    private ImageView userHeader;
    private TextView userName;
    private TextView userEmail;
    private ImageView ivSetting;
    private String TAG = this.getClass().getSimpleName();
    private DrawerLayout drawer;
    private IMallPresenter iMallPresenter;
    private Toolbar toolbar;
    private int MAX_ALPHA = 255;
    private ImageView ivProgress;
    private ActionBar actionBar;


    private void initMallInfo() {
        MallModel selectedMallModel = NexdApplication.selectedMallModel;
        if (selectedMallModel == null) {
            return;
        }
        NexdApplication.buildingName = selectedMallModel.getPyName();
        NexdApplication.buildingId = selectedMallModel.getMallId();
        selectedMallName.setError(null);
        selectedMallName.setText(selectedMallModel.getCnCityName() + "-" + selectedMallModel.getMallName());
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return getWindow().superDispatchTouchEvent(ev) ? true : onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            // 点击的是输入框区域，保留点击EditText的事件
            return event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom ? false : true;
        }
        return false;
    }


    //====================================华丽的分割线==========================================//

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//保持屏幕不变黑
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        iCollectionPresenter = new ICollectionPresenterImpl(this, this);
        iMallPresenter = new IMallPresenterImpl(this, this);
        //==============================华丽的分割线================================//
        initData();
        initToolBarView();
        initDrawerLayout();
        initView();
        initMallInfo();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }


    private void initData() {

        checkIsExistMallInfo();
        MallModel selectedMallModel = NexdApplication.selectedMallModel;
        if (selectedMallModel == null) {
            Toast.makeText(MainActivity.this, "请选择商场~", Toast.LENGTH_SHORT).show();
        }
    }


    private void checkIsExistMallInfo() {
        if (NexdApplication.malls.size() != 0) {
            NexdApplication.malls.clear();
        }
        ReadFileAsync readFileAsync = new ReadFileAsync();
        readFileAsync.execute();
    }

    private void initView() {
        ivProgress = (ImageView) findViewById(R.id.imageview_progress);
        View viewEnvironment = findViewById(R.id.main_view_environment_detail);
        etInputFloorName = (EditText) findViewById(R.id.edit_input_buidling_floor);
        tvEnvironmentWifi = (TextView) viewEnvironment.findViewById(R.id.main_environment_wifi);
        selectedMallName = (TextView) viewEnvironment.findViewById(R.id.main_mall_name);
        tvEnvironmentBeacon = (TextView) viewEnvironment.findViewById(R.id.main_environment_beacon);
        btnStartEnd = (CircularProgressButton) findViewById(R.id.button_start_collector);
        tvDevInfo = (TextView) findViewById(R.id.main_dev_info);
        iCollectionPresenter.getDeviceInfo();
        btnStartEnd.setProgress(CircularProgressButton.IDLE_STATE_PROGRESS);
        // 开始按钮 长短点击事件监听
        btnStartEnd.setOnClickListener(this);
        btnStartEnd.setOnLongClickListener(this);
        // 设置点击选择商场按钮
        // btnSelectMall.setOnClickListener(this);
        // 初始化左侧的抽屉
        drawable = new CircularProgress.Builder()
                .setRingWidth(getResources().getDimensionPixelSize(R.dimen.drawable_ring_size))
                .setOutlineColor(ContextCompat.getColor(this, android.R.color.darker_gray))
                .setRingColor(ContextCompat.getColor(this, android.R.color.transparent))
                .setCenterColor(ContextCompat.getColor(this, android.R.color.holo_green_dark))
                .create();
        drawable.setCircleScale(0f);
        drawable.setTextColor(ContextCompat.getColor(this, R.color.account_settings_avatar_border_outside_color));
        ivProgress.setImageDrawable(drawable);
        drawable.setTextSize(60);
    }

    private void initDrawerLayout() {
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        View header = null;
        if (navigationView != null) {
            header = navigationView.getHeaderView(0);
            navigationView.setNavigationItemSelectedListener(this);
            navigationView.setSelected(true);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            header.setLayoutParams(params);
            userHeader = (CircleImageView) header.findViewById(R.id.userHeader);
            userName = (TextView) header.findViewById(R.id.userName);
            userEmail = (TextView) header.findViewById(R.id.userEmail);
            userName.setText(NexdApplication.userName);
            userEmail.setText(NexdApplication.userEmial);
        }
    }

    private void initToolBarView() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawerToggle = new ActionBarDrawerToggle(
                    this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
            drawer.setDrawerListener(drawerToggle);
            if (actionBar == null && getSupportActionBar() != null) {
                actionBar = getSupportActionBar();
            }
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
            actionBar.setHomeButtonEnabled(true);
            viewSelectBuildingLayout = findViewById(R.id.main_select_building);
            ivSetting = (ImageView) findViewById(R.id.main_iv_setting);
            tvSelectBuilding = (TextView) findViewById(R.id.main_tv_select_build);
            drawerToggle.syncState();
            ivSetting.setOnClickListener(this);
            tvSelectBuilding.setOnClickListener(this);
        }

    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();

    }


    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initMallInfo();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        if (isRunning) {
            currentAnimation = startCollectorAnimation();
            currentAnimation.start();
        } else {
            iCollectionPresenter.initCollector();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        if (currentAnimation != null && currentAnimation.isRunning()) {
            currentAnimation.cancel();
        }
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();

    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    //    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.nav_figure:
                Log.d(TAG, "onNavigationItemSelected: 点击了指导手册");
                startActivity(new Intent(MainActivity.this, GuideBookActivity.class));
                break;
        }
        drawer.closeDrawers();
        Log.d(TAG, "onNavigationItemSelected: 点击了Item");
        return true;
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);
    }

    /**
     * Style 1 animation will simulate a indeterminate loading while taking advantage of the inner
     * circle to provide a progress sense
     *
     * @return Animation
     */
    private AnimatorSet startCollectorAnimation() {
        drawable.text = "0";
        drawable.setOutlineColor(ContextCompat.getColor(this, android.R.color.darker_gray));
        drawable.setRingColor(ContextCompat.getColor(this, R.color.cpb_blue_dark));
        AnimatorSet animation = new AnimatorSet();
        final ObjectAnimator indeterminateAnimation = ObjectAnimator.ofFloat(drawable, CircularProgress.PROGRESS_PROPERTY, 0, 3600);
        indeterminateAnimation.setDuration(3600);
        indeterminateAnimation.setRepeatCount(-1);
        indeterminateAnimation.setRepeatMode(Animation.REVERSE);

        ObjectAnimator centerColor = ObjectAnimator.ofObject(drawable, CircularProgress.CIRCLE_COLOR_PROPERTY, new ArgbEvaluator(), Color.argb(0, 149, 200, 233), Color.argb(MAX_ALPHA, 82, 130, 33));
        centerColor.setDuration(3600);
        centerColor.setRepeatCount(-1);
        centerColor.setRepeatMode(Animation.REVERSE);

        ObjectAnimator outLineColor = ObjectAnimator.ofObject(drawable, CircularProgress.OUTLINE_COLOR_PROPERTY, new ArgbEvaluator(), ContextCompat.getColor(this, android.R.color.darker_gray), ContextCompat.getColor(this, android.R.color.transparent));
        centerColor.setDuration(3600);
        centerColor.setRepeatCount(-1);
        centerColor.setRepeatMode(Animation.REVERSE);

        ObjectAnimator innerCircleAnimation = ObjectAnimator.ofFloat(drawable, CircularProgress.CIRCLE_SCALE_PROPERTY, 0f, 1.0f);
        innerCircleAnimation.setDuration(3600);
        innerCircleAnimation.setRepeatCount(-1);
        innerCircleAnimation.setRepeatMode(Animation.REVERSE);
        innerCircleAnimation.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                ivProgress.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
                drawable.setIndeterminate(true);
            }


            @Override
            public void onAnimationEnd(Animator animation) {
                ivProgress.setLayerType(View.LAYER_TYPE_NONE, null);
                indeterminateAnimation.end();
                drawable.setRingColor(ContextCompat.getColor(MainActivity.this, R.color.cpb_blue_dark));
                drawable.setIndeterminate(false);
                drawable.setProgress(0);
            }
        });


        animation.playTogether(innerCircleAnimation, indeterminateAnimation, centerColor, outLineColor/*, textColor, textSize*/);
        return animation;
    }


    private AnimatorSet stopCollectorAnimation() {
        AnimatorSet animation = new AnimatorSet();
        final ObjectAnimator indeterminateAnimation = ObjectAnimator.ofFloat(drawable, CircularProgress.PROGRESS_PROPERTY, 0, 1800);
        indeterminateAnimation.setDuration(1000);
        indeterminateAnimation.setRepeatCount(-1);
        indeterminateAnimation.setRepeatMode(Animation.REVERSE);

        ObjectAnimator centerColor = ObjectAnimator.ofObject(drawable, CircularProgress.CIRCLE_COLOR_PROPERTY, new ArgbEvaluator(), Color.argb(0, 48, 146, 212), Color.argb(MAX_ALPHA, 82, 130, 33));
        centerColor.setDuration(1000);
        centerColor.setRepeatCount(-1);
        centerColor.setRepeatMode(Animation.REVERSE);


        ObjectAnimator outLineColor = ObjectAnimator.ofObject(drawable, CircularProgress.OUTLINE_COLOR_PROPERTY, new ArgbEvaluator(), ContextCompat.getColor(this, android.R.color.transparent), ContextCompat.getColor(this, android.R.color.darker_gray));
        outLineColor.setDuration(1000);
        outLineColor.setRepeatCount(-1);
        outLineColor.setRepeatMode(Animation.REVERSE);


        ObjectAnimator ringColor = ObjectAnimator.ofObject(drawable, CircularProgress.RING_COLOR_PROPERTY, new ArgbEvaluator(), ContextCompat.getColor(this, R.color.cpb_blue_dark), ContextCompat.getColor(this, android.R.color.transparent));
        ringColor.setDuration(1000);
        ringColor.setRepeatCount(-1);
        ringColor.setRepeatMode(Animation.REVERSE);

        ObjectAnimator innerCircleAnimation = ObjectAnimator.ofFloat(drawable, CircularProgress.CIRCLE_SCALE_PROPERTY, 0f, 1.0f);
        innerCircleAnimation.setDuration(1000);
        innerCircleAnimation.setRepeatCount(-1);
        innerCircleAnimation.setRepeatMode(Animation.REVERSE);
        innerCircleAnimation.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                ivProgress.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
                animatorRunning = true;
                drawable.setIndeterminate(true);
                btnStartEnd.setClickable(false);
                drawable.text = "正在打包";
                drawable.isIndeterminate();
                iCollectionPresenter.buildFile();
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                ivProgress.setLayerType(View.LAYER_TYPE_NONE, null);
                drawable.setIndeterminate(false);
                drawable.setProgress(0);
                indeterminateAnimation.end();
                animatorRunning = false;
            }
        });

        animation.playTogether(innerCircleAnimation, indeterminateAnimation, centerColor, ringColor, outLineColor/*, textSize, textColor*/);
        return animation;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean rtnValue = true;
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_BACK:
                if (isRunning) {
                    rtnValue = false;
                } else {
                    this.finish();
                }
                break;
        }

        return rtnValue;
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.button_start_collector:


                if (!iCollectionPresenter.checkEnvironmentState()) {
                    showToast(getString(R.string.check_environment_param));
                    return;
                }

                if (!CheckPermission.checkPermission(this, "android.permission.ACCESS_COARSE_LOCATION")
                        || !CheckPermission.checkPermission(this, "android.permission.ACCESS_FINE_LOCATION")) {
                    showToast("定位权限被拒绝,无法正常使用");
                    return;
                }

                Log.d("CheckPermission", "权限检查已经通过");
                for (ExpandableModel expandableModel : NexdApplication.malls) {
                    for (MallModel selectedMall : expandableModel.getMallModels()) {
                        if (selectedMall.equals(NexdApplication.selectedMallModel)) {
                            NexdApplication.selectedMallModel = selectedMall;
                        }
                    }
                }
                if (NexdApplication.selectedMallModel == null) {
                    showToast("您当前选择的商场不存在,请重新选择");
                }

                if (TextUtils.isEmpty(selectedMallName.getText().toString())) {
                    showToast("请选择要采集的商场");
                    return;
                }
                // 处理点击开始按钮是处理事件
                if (TextUtils.isEmpty(etInputFloorName.getText().toString())) {
                    etInputFloorName.setError("请输入楼层名称");
                    etInputFloorName.requestFocus();
                    return;
                }
                if (!NexdApplication.wifi && !NexdApplication.bluetooth && !NexdApplication.mix) {
                    showToast("请至少选择一种采集方式");
                    return;
                }

                if (!isRunning) {
                    if (NexdApplication.wifi && NexdApplication.bluetooth) {
                        showToast("混合采集模式,已开启");
                    } else if (NexdApplication.wifi) {
                        showToast("Wi-Fi 采集模式,已开启");
                    } else if (NexdApplication.bluetooth) {
                        showToast("Beacon 采集模式,已开启");
                    }
                }

                if (btnStartEnd.getProgress() == CircularProgressButton.IDLE_STATE_PROGRESS) {
                    btnStartEnd.setProgress(CircularProgressButton.ERROR_STATE_PROGRESS);
                    currentAnimation = startCollectorAnimation();
                    currentAnimation.start();
                    //=====================开始采集=====================//
                    // 初始化
                    NexdApplication.startTime = DateUtil.getCurrentByType(DateUtil.YYYYMMDDhhmmss);
                    NexdApplication.mallName =
                            NexdApplication.floorName = etInputFloorName.getText().toString().replace(" ", "");
                    isRunning = true;
                    iCollectionPresenter.startCollect();
                    etInputFloorName.setHint("楼层名称");
                    etInputFloorName.setEnabled(false);

                    tvSelectBuilding.setClickable(false);
                    ivSetting.setImageResource(R.mipmap.setting);
                    ivSetting.setClickable(false);
                    drawer.setFocusable(false);
                    actionBar.setHomeButtonEnabled(false);
                    viewSelectBuildingLayout.setClickable(false);
                }
                break;

            case R.id.main_tv_select_build:
                enterActivity();
                break;
            case R.id.main_iv_setting:
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                SettingFragment settingFragment = new SettingFragment();
                settingFragment.show(fragmentTransaction, "setting");
                break;
        }
    }

    public void showToast(String msg) {
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void resetEnvironmentWifi(final String environmentWifi) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvEnvironmentWifi.setText(environmentWifi);
            }
        });

    }

    @Override
    public void resetEnvironmentBeacon(final String environmentBeacon) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvEnvironmentBeacon.setText(environmentBeacon);
            }
        });

    }

    @Override
    public void resetEnvironmentStep(String environmentStep) {
        drawable.text = environmentStep;
        drawable.invalidateSelf();
    }

    @Override
    public void resetAllView() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                isRunning = false;
                drawable.setTextColor(ContextCompat.getColor(MainActivity.this, android.R.color.holo_orange_dark));
                drawable.text = "采集停止";
                drawable.invalidateSelf();
                btnStartEnd.setClickable(true);
                etInputFloorName.setHint("请输入楼层名称");
                etInputFloorName.setEnabled(true);
                tvEnvironmentWifi.setText(String.format("%d", 0));
                tvEnvironmentBeacon.setText(String.format("%d", 0));
                btnStartEnd.setClickable(true);
                drawable.setRingColor(ContextCompat.getColor(MainActivity.this, android.R.color.transparent));
                drawable.setOutlineColor(ContextCompat.getColor(MainActivity.this, android.R.color.transparent));

                if (animatorRunning) {
                    Log.i("xzxAnimation", "动画还在进行");
                    // 动画化还在运行
                    if (currentAnimation != null) {
                        currentAnimation.cancel();
                        currentAnimation = null;
                    }
                }
            }
        });
    }

    @Override
    public void initDeviceInfo(String deviceInfo) {
        if (tvDevInfo != null) {
            tvDevInfo.setText(deviceInfo);
        }
    }

    @Override
    public boolean onLongClick(View v) {
        // 处理长按结束按钮的点击事件
        if (btnStartEnd.getProgress() == CircularProgressButton.ERROR_STATE_PROGRESS) {
            // 停止采集
            btnStartEnd.setProgress(CircularProgressButton.IDLE_STATE_PROGRESS);
            if (currentAnimation.isRunning() && currentAnimation != null) {
                currentAnimation.cancel();
            }

            iCollectionPresenter.saveOperaRecord();
            currentAnimation = stopCollectorAnimation();
            currentAnimation.start();
            iCollectionPresenter.stopCollet();

            tvEnvironmentWifi.setText(String.valueOf(0));
            tvEnvironmentBeacon.setText(String.valueOf(0));
            viewSelectBuildingLayout.setClickable(true);
            tvSelectBuilding.setClickable(true);
            ivSetting.setClickable(true);
            ivSetting.setImageResource(R.mipmap.setting_checked);
            actionBar.setHomeButtonEnabled(true);
            btnStartEnd.setClickable(false);
        }
        return true;
    }

    @Override
    public void enterActivity() {
        if (NexdApplication.malls.size() == 0) {
            Toast.makeText(MainActivity.this, getString(R.string.code_error_local_no_data), Toast.LENGTH_SHORT).show();
        } else {
            startActivity(new Intent(this, SearchActivity.class));
        }
    }


    class ReadFileAsync extends AsyncTask {
        @Override
        protected Object doInBackground(Object[] params) {
            iMallPresenter.checkIsFileIsExist();
            return null;
        }
    }
}